package com.pkx.guide.core.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.pkx.guide.common.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * mybatis-plus 字段自动填充
 *
 * @author haoxr
 * @link <a href="https://mp.baomidou.com/guide/auto-fill-metainfo.html">官方文档</a>
 * @since 2022/10/14
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 创建人员ID
     */
    private static final String CREATE_USER_ID = "createUserId";

    /**
     * 创建时间
     */
    private static final String CREATE_TIME = "createTime";

    /**
     * 更新人id
     */
    private static final String UPDATE_USER_ID = "updateUserId";

    /**
     * 更新时间
     */
    private static final String UPDATE_TIME = "updateTime";

    /**
     * 删除标记
     */
    private static final String DEL_FLG = "delFlg";

    /**
     * 新增填充创建时间
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        setFieldValByName(CREATE_USER_ID, SecurityUtils.getUserId() == null? -1: SecurityUtils.getUserId(), metaObject);
        setFieldValByName(CREATE_TIME, new Date(), metaObject);
        setFieldValByName(UPDATE_USER_ID, SecurityUtils.getUserId() == null? -1: SecurityUtils.getUserId(), metaObject);
        setFieldValByName(UPDATE_TIME, new Date(), metaObject);
        setFieldValByName(DEL_FLG, 0, metaObject);
    }

    /**
     * 更新填充更新时间
     *
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        setFieldValByName(UPDATE_USER_ID, SecurityUtils.getUserId() == null? -1: SecurityUtils.getUserId(), metaObject);
        setFieldValByName(UPDATE_TIME, new Date(), metaObject);
    }

}
